﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using CommonApp.Models;
using IBS.Bll;
using IBS.Model;
using IBS.ServiceContracts;

namespace BankApp.Controllers
{
    [Authorize(Roles = "Operator")]
    public class RequestsController : Controller
    {
        private IKnowledgeBaseService knowledgeBaseService;
        private IAuthorityService authorityService;
        private IStreetService streetService;

        public RequestsController()
        {
            var container = new IbsContainer();
            this.knowledgeBaseService = container.KnowledgeBaseService;
            this.authorityService = container.AuthorityService;
            this.streetService = container.StreetService;
        }

        public ActionResult Index(string firstName = null, string lastName = null, string error = null)
        {
            ViewBag.FirstName = firstName;
            ViewBag.LastName = lastName;

            var allRequestsResult = authorityService.GetRegRequests();
            var model = Mapper.Map<IList<Request>, IList<UserRequest>>(allRequestsResult)
                .Where(_ => (String.IsNullOrWhiteSpace(firstName) || _.FirstName.ToUpper() == firstName.ToUpper())
                         && (String.IsNullOrWhiteSpace(lastName) || _.LastName.ToUpper() == lastName.ToUpper()))
                .ToList();

            ModelState.AddModelError("", error);
            return View(model);
        }

        //
        // GET: /Request/Details/5

        public ActionResult Details(int id)
        {
            var getRequestResult = authorityService.GetRegRequestById(id);
            var userRequest = Mapper.Map<UserRequest>(getRequestResult);
            var client = knowledgeBaseService
               .GetClients(c => c.PassportNumber == userRequest.PassportNumber 
                             && c.PassportSeries == userRequest.PassportSeries)
               .SingleOrDefault();
            if (client != null)
                userRequest.ClientId = client.Id;
            return View(userRequest);
        }

        //
        // GET: /Request/Create


        public ActionResult RegisterUser(int id, int? clientId)
        {
            try
            {
                var codeCard = authorityService.GetUnmatchedCodeCards().FirstOrDefault();
                if (codeCard == null)
                {
                    return RedirectToAction("Index", new { Error = "There's no available code cards" });
                }
                var request = authorityService.GetRegRequestById(id);
                if (clientId == null)
                {
                    knowledgeBaseService.CreateClient(new IBS.Model.Client
                        {
                            FirstName = request.FirstName,
                            LastName = request.LastName,
                            PassportNumber = request.PassportNumber,
                            PassportSeries = request.PassportSeries,
                            DateOfBirth = request.DateOfBirth,
                            Patronymic = request.Patronymic,
                        }, 2, 2, User.Identity.Name);

                    clientId = knowledgeBaseService
                        .GetClients(
                            c =>
                            c.PassportNumber == request.PassportNumber && c.PassportSeries == request.PassportSeries)
                        .Single().Id;
                }

                authorityService.CreateUser(clientId.Value, codeCard, request.Login, request.Password, request.Email);
                authorityService.DeleteRegRequest(request.Id);
                
            }
            catch (BusinessException ex)
            {
                return RedirectToAction("Index", new { Error = ex.Message });
            }
            return RedirectToAction("Index", "Clients");
        }

        public ActionResult Notify(int id)
        {
            authorityService.AproveRegRequest(id, HttpContext.User.Identity.Name);
            
            return RedirectToAction("Index");
        }

        public ActionResult Reject(int id)
        {
            authorityService.RejectRegRequest(id, HttpContext.User.Identity.Name);

            return RedirectToAction("Index");
        }
    }
}
